// import { MQTT_OTA_DTO } from '@dto/mqtt.dto';
import { envConfig } from '@config';
import { Body, Controller, Get, Inject, Post } from '@midwayjs/core';
import { FirmwareService } from '@service/firmware/firmware.service';
import { OtaTaskService } from '@service/firmware/ota_task.service';
import { MqttService } from '@service/mqtt.service';
import { resBuild } from '@utils/resBuild';
@Controller('/mqtt')
export class MqttController {
  @Inject()
  mqttService: MqttService;
  @Inject()
  firmwareService: FirmwareService;
  @Inject()
  otaTaskService: OtaTaskService;

  // 获取buffer
  @Get('/')
  async getMessage() {
    await this.mqttService.init()
  }
  // 发布消息接口 (下发ota)
  @Post('/ota')
  async publish(@Body() ota) {
    console.log('触发ota....', ota)
    // if (ota == undefined) {
    //   ota = {
    //     "action": "wristband.ota",
    //     "url": "http://test.shanghai1.zhiyu.school/firmware/3c70b175-3631-4c8b-ab32-bae31a19d399_C1-65_fw.bin",
    //     "version": 65,
    //     "localPath": "/store/firmware/C1-65_fw.bin",
    //     "force": false
    //   }
    // }
    // 先根据 firmwareid 判断它是什么类型(访问firmware表)
    // 根据 ota.firmwareid 查 firmware 表 对应数据
    let firmware = ota.firmware
    let firmware1 = ota.firmware1
    console.log('对应的固件', firmware)
    let body = {
      id: ota.id,
      firmwareid: ota?.firmwareid,
      firmwareid_1: ota?.firmwareid_1,
      gw_mac: ota.gw_mac,
      wb_mac: ota.wb_mac,
      full: ota.full === 'true' || ota.full === true,
      gw_full: ota.gw_full === 'true' || ota.gw_full === true,
      wb_full: ota.wb_full === 'true' || ota.wb_full === true,
      updateMode: ota.updateMode,
      path: ota.path,
      remain: ota.duration ? false : true, // 是否需要保持升级状态
      duration: ota.duration || null, // 手环升级时长（如果 duration 是 0 或者 null，表示不限制时长，就是长期升级）
      wb_count: ota.wb_count || null, // 手环升级数量
    };
    let otaTask = {}
    if(!firmware && !firmware1){
      return resBuild.fail("固件不存在，请上传正确的固件文件！")
    }
    // 如果是手环固件
    if (firmware?.firmwareType?.includes('wb')) {
      otaTask = {
        taskId: ota.id,
        action: "wb-ota",
        // url: `http://test.shanghai1.zhiyu.school/firmware/${firmware.path.split("\\").pop()}`, // 本地路径有 \\ ，服务器直接 / 就可以
        url: `${envConfig.SAVE_PATH}/${firmware.path.split("/").pop()}`,
        version: firmware?.version,
        localPath: ota.path,
        // force: body.force,
        wb_mac: ota.wb_mac, // 指定手环升级
        method: body.updateMode,// method:
        duration: ota.duration || null, // 手环升级时长
        wb_full: body.wb_full, // 是否需要保持升级状态
        remain: body.remain, // 是否需要保持升级状态
        wb_count: ota.wb_count || null, // 手环升级数量
      }
    }
    if (firmware?.firmwareType?.includes('gw') || firmware1?.firmwareType?.includes('gw')) {
      otaTask = {
        taskId: ota.id,
        action: "gw-ota",
        // url: `http://test.shanghai1.zhiyu.school/firmware/${firmware.path.split("\\").pop()}`, // 本地路径有 \\ ，服务器直接 / 就可以
        url_bin: !!firmware ? `${envConfig.SAVE_PATH}/${firmware?.path.split("/").pop()}` : null,
        url_fs: !!firmware1 ? `${envConfig.SAVE_PATH}/${firmware1?.path.split("/").pop()}` : null,
        version_bin: firmware?.version,
        version_fs: firmware1?.version,
        gw_full: body.gw_full, // 是否需要保持升级状态
        // force: body.force,
        method: body.updateMode,
        checksum_bin: firmware?.file?.checksum, // 固件校验是否一致（bin）
        checksum_fs: firmware1?.file?.checksum, // 固件校验是否一致（fs）
      }
    }
    console.log('otaTask 上报数据', otaTask)
    console.log('传入的ota', ota.gw_mac)
    if (body.gw_full) {
      await this.mqttService.clientSuZhouToPublish(undefined, otaTask);
    } else {
      console.log('ota.gw_mac.indexOf(', ')', ota.gw_mac.indexOf(','))
      if (ota.gw_mac.includes(',')) {
        console.log('传入的网关', ota.gw_mac)
        // gw_mac 字符串拆分
        let gwMacList = ota.gw_mac.includes(',') ? ota.gw_mac.split(',') : [ota.gw_mac];
        gwMacList.forEach(async (item) => {
          await this.mqttService.clientSuZhouToPublish(item, otaTask);
        })
      } else {
        console.log('一个网关', ota.gw_mac)
        // 直接下发给网关
        await this.mqttService.clientSuZhouToPublish(ota.gw_mac, otaTask);
      }
    }
    // 存至数据库 ota_task
    await this.otaTaskService.createOtaTask(body);
    return resBuild.success('下发 ota 完成!');
  }

  // 闪灯/鸣笛等对于网关操作控制上报
  @Post('/toGwControl')
  async toGwControl(@Body() params) {
    try {
      //  将所传的参数上报给网关
      await this.mqttService.clientSuZhouToPublish(params.mac, params)
      return resBuild.success("控制成功")
    } catch (err) {
      return resBuild.fail("控制失败")
    }
  }

}
